#include "fdfs_api.h"
#include <stdio.h>
#include "make_log.h"
#include "mysql_conn.h"
#include "cfg.h"
#include <sys/time.h>
#include "cJSON.h"
#include "fcgi_stdio.h"
#include <string.h>
#include "utils.h"
#include "mysql_conn.h"
#include <stdlib.h>

static char mysql_user[128] = {0};
static char mysql_pwd[128] = {0};
static char mysql_db[128] = {0};

//redis 服务器ip、端口
static char redis_ip[30] = {0};
static char redis_port[10] = {0};

void get_share_files_count();
int get_fileslist_json_info(char *buf, int *p_start, int *p_count);
int get_share_filelist(int start, int count, char* cmd);

int main()
{
    char cmd[20] = {0};

    read_cfg(mysql_user, mysql_pwd, mysql_db);
    get_cfg_value(CFG_PATH, "redis", "ip", redis_ip);
    get_cfg_value(CFG_PATH, "redis", "port", redis_port);

    while(FCGI_Accept() >= 0)
    {
        printf("Content-type: text/html; charset=utf8\r\n\r\n");

        char* query_string = getenv("QUERY_STRING");

        parse_get_params(query_string, "cmd", cmd, NULL);
        LOG("cmd = %s\n", cmd);

        if(strcmp(cmd, "count") == 0)
        {
            get_share_files_count();
        }
        else
        {
            char* contentLength = getenv("CONTENT_LENGTH");
            int len;
            if(contentLength == NULL)
            {
                len = 0;
            }
            else
            {
                len = atoi(contentLength);
            }

            if(len <= 0)
            {
                LOG("len <= 0\n");
                continue;
            }
            else
            {
                char buf[4*1024] = {0};
                int ret = 0;
                ret = fread(buf, 1, len, stdin);
                if(ret == 0)
                {
                    LOG("fread() error\n");
                    continue;
                }

                LOG("buf = %s\n", buf);

                //获取共享文件信息 127.0.0.1:80/sharefiles&cmd=normal
                //按下载量升序 127.0.0.1:80/sharefiles?cmd=pvasc
                //按下载量降序127.0.0.1:80/sharefiles?cmd=pvdesc

                int start = 0;
                int count = 0;
                get_fileslist_json_info(buf, &start, &count);
                LOG("start = %d, count = %d\n", start, count);
                if(strcmp(cmd, "normal") == 0)
                {
                    get_share_filelist(start, count, cmd);
                }
                else if(strcmp(cmd, "pvasc") == 0)
                {
                    get_share_filelist(start, count, cmd);
                }
                else if(strcmp(cmd, "pvdesc") == 0)
                {
                    get_share_filelist(start, count, cmd);
                }
            }
        }
    }
    return 0;
}

void get_share_files_count()
{
    char sql_cmd[1024] = {0};
    MYSQL* conn = NULL;
    long line = 0;

    do
    {
        conn = get_mysql(mysql_user, mysql_pwd, mysql_db);
        if(conn == NULL)
        {
            LOG("get_mysql error\n");
            break;
        }

        mysql_query(conn, "set names utf8mb4");

      //  sprintf(sql_cmd, "select count from user_file_count where user = '%s'", "xxx_share_xxx_file_xxx_list_xxx_count_xxx");
	sprintf(sql_cmd, "select count from user_file_count where user = '%s'", "xxx_share_xxx_file_xxx_list_xxx_count_xxx");
        char tmp[512] = {0};
        int ret2 = process_result_one(conn, sql_cmd, tmp);
        if(ret2 != 0)
        {
            LOG("%s 操作失败\n", sql_cmd);
            break;
        }

        line = atol(tmp);
    }while(0);

    if(conn != NULL)
    {
        mysql_close(conn);
        conn = NULL;
    }

    LOG("line = %ld\n", line);
    printf("%ld", line);
}

//解析的json包
int get_fileslist_json_info(char *buf, int *p_start, int *p_count)
{
    int ret = 0;

    /*json数据如下
    {
        "start": 0
        "count": 10
    }
    */

    //解析json包
    //解析一个json字符串为cJSON对象
    cJSON * root = cJSON_Parse(buf);
    if(NULL == root)
    {
        LOG("cJSON_Parse err\n");
        ret = -1;
        goto END;
    }

    //文件起点
    cJSON *child2 = cJSON_GetObjectItem(root, "start");
    if(NULL == child2)
    {
        LOG("cJSON_GetObjectItem err\n");
        ret = -1;
        goto END;
    }

    *p_start = child2->valueint;

    //文件请求个数
    cJSON *child3 = cJSON_GetObjectItem(root, "count");
    if(NULL == child3)
    {
        LOG("cJSON_GetObjectItem err\n");
        ret = -1;
        goto END;
    }

    *p_count = child3->valueint;

END:
    if(root != NULL)
    {
        cJSON_Delete(root);//删除json对象
        root = NULL;
    }

    return ret;
}

//获取共享文件列表
//获取用户文件信息 127.0.0.1:80/sharefiles&cmd=normal
int get_share_filelist(int start, int count, char* cmd)
{
    int ret = 0;
    char sql_cmd[1024] = {0};
    MYSQL* conn = NULL;
    cJSON* root = NULL;
    cJSON* array = NULL;
    cJSON* item = NULL;
    char* out = NULL;
    char* out2 = NULL;
    MYSQL_RES* res_set = NULL;

    do
    {
        conn = get_mysql(mysql_user, mysql_pwd, mysql_db);
        if(NULL == conn)
        {
            LOG("get_mysql error\n");
            ret = -1;
            break;
        }

        mysql_query(conn, "set names utf8mb4");

        if(strcmp(cmd, "pvasc"))
        {
            sprintf(sql_cmd, "select share_file_list.*, file_info.url, file_info.size, file_info.type from file_info, share_file_list where file_info.md5 = share_file_list.md5 order by pv asc limit %d, %d", start, count);
        }
        else if(strcmp(cmd, "pvdesc"))
        {
            sprintf(sql_cmd, "select share_file_list.*, file_info.url, file_info.size, file_info.type from file_info, share_file_list where file_info.md5 = share_file_list.md5 order by pv desc limit %d, %d", start, count);
        }
        else
        {
            sprintf(sql_cmd, "select share_file_list.*, file_info.url, file_info.size, file_info.type from file_info, share_file_list where file_info.md5 = share_file_list.md5 limit %d, %d", start, count);
        }

        LOG("%s 在操作\n", sql_cmd);

        if(mysql_query(conn, sql_cmd) != 0)
        {
            LOG("%s 操作失败: %s\n", sql_cmd, mysql_error(conn));
            ret = -1;
            break;
        }

        res_set = mysql_store_result(conn);
        if(res_set == NULL)
        {
            LOG("mysql_store_result error\n");
            ret = -1;
            break;
        }

        unsigned long line = 0;
        line = mysql_num_rows(res_set);
        if(line == 0)
        {
            LOG("mysql_num_rows(res_set) error!\n");
            ret = -1;
            break;
        }

        MYSQL_ROW row;

        root = cJSON_CreateObject();
        array = cJSON_CreateArray();

        while((row = mysql_fetch_row(res_set)) != NULL)
        {
            item = cJSON_CreateObject();
             /*
            {
            "user": "milo",
            "md5": "e8ea6031b779ac26c319ddf949ad9d8d",
            "create_time": "2020-06-21 21:35:25",
            "file_name": "test.mp4",
            "share_status": 1,
            "pv": 0,
            "url": "http://192.168.31.109:80/group1/M00/00/00/wKgfbViy2Z2AJ-FTAaM3As-g3Z0782.mp4",
            "size": 27473666,
            "type": "mp4"
            }
            */
            int column_index = 0;
            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "user", row[++column_index]);
            }

            column_index++;
            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "md5", row[column_index]);
            }

            column_index++;

            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "file_name", row[column_index]);
            }
            column_index++;

            if(row[column_index] != NULL)
            {
                cJSON_AddNumberToObject(item, "pv", atol(row[column_index]));
            }
            cJSON_AddNumberToObject(item, "share_status", 1);

            column_index++;
            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "create_time", row[column_index]);
            }


            column_index++;
            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "url", row[column_index]);
            }

            column_index++;
            if(row[column_index] != NULL)
            {
                cJSON_AddNumberToObject(item, "size", atol(row[column_index]));
            }

            column_index++;
            if(row[column_index] != NULL)
            {
                cJSON_AddStringToObject(item, "type", row[column_index]);
            }

            cJSON_AddItemToArray(array, item);
        }

        cJSON_AddItemToObject(root, "files", array);

        out = cJSON_Print(root);

        LOG("%s\n", out);
    }while(0);

    if(ret == 0)
    {
        printf("%s", out);
        free(out);
        out = NULL;
    }
    else
    {
        out2 = NULL;
        out2 = return_status("015");
    }
    if(out2 != NULL)
    {
        printf(out2);
        free(out2);
    }
    if(res_set != NULL)
    {
        mysql_free_result(res_set);
    }
    if(conn != NULL)
    {
        mysql_close(conn);
    }
//     if(item != NULL)
//     {
//         cJSON_Delete(item);
//         item = NULL;
//     }
// LOG("dfdsfs");
//     if(array != NULL)
//     {
//         cJSON_Delete(array);
//         array = NULL;
//     }
// LOG("dfdsfs");
    //这个语句会递归地遍历 root 对象树，释放所有分配的内存，包括 array 和 item 对象占用的内存。
    if(root != NULL)
    {
        cJSON_Delete(root);
        root = NULL;
    }
    if(out != NULL)
    {
        free(out);
        out = NULL;
    }
    return ret;
}
